<?php

namespace app\aiv110\controller;

use app\aiv110\controller\CommonController;
use think\Validate;
use think\Db;
use app\util\Utils;
use app\aiv110\model\StaffCtm;
use app\aiv110\model\Staff;
use app\aiv110\model\Yuyue;
use app\util\File;
use app\aiv110\model\StaffEnlist;

class StaffController extends CommonController {
    /*
     * code列表
     */

    public function code() {
        /*
         * 0  成功
         * 1  参数错误
         * 2  验证失败
         * 60000  您已经申请过了，请耐心等待
         * 60001 
         * 60002  
         * 60003
         * 60004
         */
    }

    /*
     * 记录用户浏览美容师页面
     * 日期 2019-11-07
     */

    public function ctmBrowseStaff() {
        $rule = [
            'ctm_id' => 'require',
            'staff_id' => 'require',
        ];
        $msg = [
            'ctm_id.require' => '用户id必须',
            'staff_id.require' => '美容师id必须',
        ];

        $all = input('param.');

        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();

            return Utils::ajaxReturn(1, $error, null);
        }

        $ctm_id = $all['ctm_id'];
        $staff_id = $all['staff_id'];

        //写入数据
        $staffCtmResult = StaffCtm::insert([
                    'staff_id' => $staff_id,
                    'ctm_id' => $ctm_id,
                    'add_time' => date('Y-m-d H:i:s'),
        ]);
        if ($staffCtmResult) {
            return Utils::ajaxReturn(0, '添加成功', null);
        }
    }

    /*
     * 查询美容师的姓名
     * 日期 2020-01-13
     */

    public function getStaffName() {
        $rule = [
            'staff_id' => 'require',
        ];
        $msg = [
            'staff_id.require' => '美容师id必须',
        ];

        $all = input('param.');

        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();

            return Utils::ajaxReturn(1, $error, null);
        }

        $staff_id = $all['staff_id'];

        //写入数据
        $name = Staff::where('id', $staff_id)->field('staff_name')->find();

        return Utils::ajaxReturn(0, '查询成功', $name);
    }

    /*
     * 美容师考核得分
     * 日期 2021-01-18
     * 
     * 【出勤分】当月出勤满22天，基础分加20分  #已经在打卡接口实时更新了
     * 【出勤分】当月完单数≥30单，基础分加30分  #美容师开始服务的时间计算  具体单数根据团队设定而定
     * 【出勤分】高峰期接单，高峰分加1.5分  #每日下午6:00至晚上9:00为高峰期  在这期间美容师开始服务
     * 【服务分】每月初始分，加80分  #一个月加一次  每个月1号跑其他任务   
     * 【服务分】用户5星好评，加XX分  #服务完成3天内评价的有效  用户评分：5星好评服务分加分0.50分，4星评价不加分，3星评价-0.50分，2星评价-0.75分，1星评价-1.00分
     * 【服务分】用户X星评价，减XX分  
     * 【服务分】接单及时，加0.25分  #美容师在工作时间内（9:00-21:00）应及时接单。在1小时内接单+0.25分，超过3小时未接单-0.5分。拒绝接单-1.00分 在美容师服务完成后计算
     * 【服务分】接单不及时，减0.5分 #当时马上扣分
     * 【服务分】顾客400投诉，减5分  #后台客服 第二天显示
     * 【服务分】顾客因服务不满意退单，减10分   #7天后跑 服务完成7天跑  原因为 服务不满意
     * 【服务分】仪容不整，或未穿工作制服，减3分   #根据问卷调查  累计3次扣分
     * 【服务分】行为不文明，减3分  #根据问卷调查  累计3次扣分
     * 【服务分】未佩戴口罩，或卫生脏乱，减4分  #根据问卷调查  累计3次扣分
     * 【服务分】服务态度不佳，减5分  #根据问卷调查  累计3次扣分
     */

    public function staffScore() {
        $d = date('j', time());
        if ($d == '1') {
            $monthBeginDate = date('Y-m-01 00:00:00', strtotime('last month')); //上月开始时间
            $monthendDate = date('Y-m-d 23:59:59', strtotime(date('Y-m-1') . '-1 day')); //本月结束时间
            $a = mktime(0,0,0,date('m'),1,date('Y')) -1 ;
            $addTime = date('Y-m-d H:i:s',$a);//如果是1号添加时间记录为上个月
        } else {
            $monthBeginDate = date('Y-m-01 00:00:00', strtotime(date("Y-m-d"))); //本月开始时间
            $monthendDate = date('Y-m-d 23:59:59', strtotime("$monthBeginDate +1 month -1 day")); //本月结束时间
            $addTime = date('Y-m-d H:i:s');
        }
        //print_r($d.'========='.$monthBeginDate.'===='.$monthendDate);die;
        $yesterdayBeginDate = date('Y-m-d H:i:s', strtotime(date("Y-m-d", strtotime("-1 day")))); //昨天开始时间
        $yesterdayEndDate = date('Y-m-d H:i:s', strtotime(date("Y-m-d", strtotime("-1 day"))) + 86399); //昨天结束时间

        $sevenDaysAgoBeginDate = date('Y-m-d H:i:s', strtotime(date("Y-m-d", strtotime("-7 day")))); //7天前开始时间
        $sevenDaysAgoEndDate = date('Y-m-d H:i:s', strtotime(date("Y-m-d", strtotime("-7 day"))) + 86399); //7天前结束时间

        $fiveDaysAgoBeginDate = date('Y-m-d H:i:s', strtotime(date("Y-m-d", strtotime("-5 day")))); //5天前开始时间
        $fiveDaysAgoEndDate = date('Y-m-d H:i:s', strtotime(date("Y-m-d", strtotime("-5 day"))) + 86399); //5天前结束时间

        $yesterday9 = date('Y-m-d H:i:s', mktime(9, 0, 0, date("m"), date("d") - 1, date("Y"))); //昨天9的时间
        $yesterday18 = date('Y-m-d H:i:s', mktime(18, 0, 0, date("m"), date("d") - 1, date("Y"))); //昨天18的时间
        $yesterday21 = date('Y-m-d H:i:s', mktime(21, 0, 0, date("m"), date("d") - 1, date("Y"))); //昨天21点的时间

        $staffList = Staff::where('staff_on', 1)->where('status', 1)->where('staff_is_creator', 0)->column('id');
        for ($i = 0; $i < count($staffList); $i++) {
            $staff_id = $staffList[$i];
            //查询美容师当月的 接单达标分是否添加
            $serScore = Db::name('staff_assess_score')
                    ->where('staff_id', $staff_id)
                    ->where('score_type', 5)
                    ->where('add_time', 'between', [$monthBeginDate, $monthendDate])
                    ->find();
            if (empty($serScore)) {
                $team_id = Db::name('staff_team_details')
                        ->where('staff_id', $staff_id)
                        ->where('status', 1)
                        ->value('team_id'); //美容师所在的团队id
                //当月完单数≥30单，基础分加30分
                if ($team_id) {
                    $base_service_num = Db::name('staff_team')->where('id', $team_id)->value('base_service_num');
                    $yuyueNum = Yuyue::where('staff_id', $staff_id)
                            ->where('status', 'in', '4,7,8')
                            ->where('staff_time', 'between', [$monthBeginDate, $monthendDate])
                            ->count();
                    if ($yuyueNum >= $base_service_num) {
                        $serdata['staff_id'] = $staff_id;
                        $serdata['type'] = 1;
                        $serdata['score_type'] = 5;
                        $serdata['score'] = 30;
                        $serdata['remarks'] = '当月完单数≥' . $base_service_num . '单，基础分加30分';
                        $serdata['add_time'] = $addTime;
                        Db::name('staff_assess_score')->insert($serdata);
                    }
                }
            }
            //高峰期接单，高峰分加1.5分  #每日下午6:00至晚上9:00为高峰期  在这期间美容师开始服务
            $gaofengYuyueList = Yuyue::where('staff_id', $staff_id)
                    ->where('status', 'in', '4,7,8')
                    ->where('staff_time', 'between', [$yesterday18, $yesterday21])
                    ->field('id,staff_time')
                    ->select();
            if ($gaofengYuyueList) {
                foreach ($gaofengYuyueList as $k => $v) {
                    $gaofengScore = Db::name('staff_assess_score')
                            ->where('order_id', $v['id'])
                            ->where('score_type', 4)
                            ->find();
                    if (empty($gaofengScore)) {
                        $gaofengdata['staff_id'] = $staff_id;
                        $gaofengdata['type'] = 1;
                        $gaofengdata['score_type'] = 4;
                        $gaofengdata['score'] = 1.5;
                        $gaofengdata['remarks'] = '高峰期接单，高峰分加1.5分';
                        $gaofengdata['order_id'] = $v['id'];
                        $gaofengdata['add_time'] = $v['staff_time'];
                        Db::name('staff_assess_score')->insert($gaofengdata);
                    }
                }
            }
            //服务完成3天内评价的有效  
            //用户评分：5星好评服务分加分0.50分，4星评价不加分，3星评价-0.50分，2星评价-0.75分，1星评价-1.00分
            $pingjiaList = Db::name('comment')
                    ->alias('c')
                    ->join('yuyue y', 'y.id = c.yuyue_id')
                    ->where('c.staff_id', $staff_id)
                    ->where('c.add_time', 'between', [$fiveDaysAgoBeginDate, $fiveDaysAgoEndDate])
                    ->field('c.id,c.staff_star,c.add_time,y.staff_time')
                    ->select();
            if ($pingjiaList) {
                foreach ($pingjiaList as $k => $v) {
                    $pingjiaScore = Db::name('staff_assess_score')
                            ->where('order_id', $v['id'])
                            ->where('score_type', 7)
                            ->find();
                    $pingjia_time = $v['add_time'];
                    $staff_time = $v['staff_time'];
                    $cha_time = strtotime($pingjia_time) - strtotime($staff_time);
                    if (empty($pingjiaScore) && $cha_time < 259200 && $v['staff_star'] != 4) {//3天内评价的
                        $pingjiadata['staff_id'] = $staff_id;
                        $pingjiadata['type'] = 2;
                        $pingjiadata['score_type'] = 7;
                        $staff_star = $v['staff_star'];
                        if ($staff_star == 5) {
                            $score = 0.5;
                            $remarks = '用户5星好评，加0.5分';
                        } elseif ($staff_star == 4) {
                            $score = 0;
                            $remarks = '用户4星好评，不加分';
                        } elseif ($staff_star == 3) {
                            $score = -0.5;
                            $remarks = '用户3星评价，减0.5分';
                        } elseif ($staff_star == 2) {
                            $score = -0.75;
                            $remarks = '用户2星评价，减0.75分';
                        } elseif ($staff_star == 1) {
                            $score = -1;
                            $remarks = '用户1星评价，减1分';
                        }
                        $pingjiadata['score'] = $score;
                        $pingjiadata['remarks'] = $remarks;
                        $pingjiadata['order_id'] = $v['id'];
                        $pingjiadata['add_time'] = $v['add_time'];
                        Db::name('staff_assess_score')->insert($pingjiadata);
                    }
                }
            }
            //接单及时不及时
            //美容师在工作时间内（9:00-21:00）应及时接单。在1小时内接单+0.25分，超过3小时未接单-0.5分。拒绝接单-1.00分
            $jiedanList = Yuyue::where('staff_id', $staff_id)
                    ->where('staff_time', 'between', [$yesterdayBeginDate, $yesterdayEndDate])
                    ->field('id,status,user_confirm_time,confirm_time,refused_time')
                    ->select();
            if ($jiedanList) {
                foreach ($jiedanList as $k => $v) {
                    $gaofengScore = Db::name('staff_assess_score')
                            ->where('order_id', $v['id'])
                            ->where('score_type', 'in', '8')
                            ->find();
                    $user_confirm_time = $v['user_confirm_time'];
                    $confirm_time = $v['confirm_time'];
                    $jiedancha_time = strtotime($confirm_time) - strtotime($user_confirm_time);
                    $a = strtotime($user_confirm_time);
                    $h = date('H', $a);

                    if (empty($gaofengScore)) {
                        if ($h >= 9 and $h <= 21) {
                            if ($jiedancha_time <= 3600) {
                                $jiedanscore = 0.25;
                                $score_type = 8;
                                $remarks = '接单及时，加0.25分';
                            } else {
                                $jiedanscore = '';
                            }
                        } else {
                            $jiedanscore = '';
                        }
                        if ($jiedanscore) {
                            $jiedandata['staff_id'] = $staff_id;
                            $jiedandata['type'] = 2;
                            $jiedandata['score_type'] = $score_type;
                            $jiedandata['score'] = $jiedanscore;
                            $jiedandata['remarks'] = $remarks;
                            $jiedandata['order_id'] = $v['id'];
                            $jiedandata['add_time'] = $v['confirm_time'];
                            Db::name('staff_assess_score')->insert($jiedandata);
                        }
                    }
                }
            }

            //顾客因服务不满意退单，减10分   #7天后跑 服务完成7天跑  原因为 服务不满意
            //2021.1.24号上线  所以这个任务需要在7天以后跑  也就是2021.2.1跑
            $a = strtotime($sevenDaysAgoBeginDate);
            if ($a >= 1611936000) {//小于24号不能跑  1611417600 后来改成29号0点上线
                $tuidanList = Yuyue::alias('y')
                        ->join('program_refund r', 'r.yuyue_id = y.id', 'left')
                        ->where('y.staff_id', $staff_id)
                        ->where('y.staff_time', 'between', [$sevenDaysAgoBeginDate, $sevenDaysAgoEndDate])
                        ->where('y.refund_status', 'in', '1,2')
                        ->where('r.apply_reason', '服务不满意')
                        ->field('y.id,y.staff_time')
                        ->select();
                if ($tuidanList) {
                    foreach ($tuidanList as $k => $v) {
                        $tuidanScore = Db::name('staff_assess_score')
                                ->where('order_id', $v['id'])
                                ->where('score_type', 11)
                                ->find();
                        if (empty($tuidanScore)) {
                            $tuidandata['staff_id'] = $staff_id;
                            $tuidandata['type'] = 2;
                            $tuidandata['score_type'] = 11;
                            $tuidandata['score'] = -10;
                            $tuidandata['remarks'] = '顾客因服务不满意退单，减10分';
                            $tuidandata['order_id'] = $v['id'];
                            $tuidandata['add_time'] = $v['staff_time'];
                            Db::name('staff_assess_score')->insert($tuidandata);
                        }
                    }
                }
            }
            //【服务分】仪容不整，或未穿工作制服，减3分   #根据问卷调查  累计3次扣分
            $wenjuan1 = Db::name('survey_logs')
                    ->where('staff_id', $staff_id)
                    ->where('type', 12)
                    ->where('yes_no', 0)
                    ->where('is_deduct', 2)
                    ->where('add_time', 'between', [$monthBeginDate, $monthendDate])
                    ->limit(0, 3)
                    ->order('add_time asc')
                    ->field('id,add_time')
                    ->select();
            $num1 = count($wenjuan1);
            if ($num1 == 3) {
                Db::name('survey_logs')
                        ->where('id', 'in', [$wenjuan1[0]['id'], $wenjuan1[1]['id'], $wenjuan1[2]['id']])
                        ->update(['is_deduct' => 1]);

                $wenjuan1data['staff_id'] = $staff_id;
                $wenjuan1data['type'] = 2;
                $wenjuan1data['score_type'] = 12;
                $wenjuan1data['score'] = -3;
                $wenjuan1data['remarks'] = '仪容不整，或未穿工作制服，减3分';
                $wenjuan1data['order_id'] = $wenjuan1[2]['id'];
                $wenjuan1data['add_time'] = $wenjuan1[2]['add_time'];
                Db::name('staff_assess_score')->insert($wenjuan1data);
            }

            //【服务分】行为不文明，减3分  #根据问卷调查  累计3次扣分
            $wenjuan2 = Db::name('survey_logs')
                    ->where('staff_id', $staff_id)
                    ->where('type', 13)
                    ->where('yes_no', 0)
                    ->where('is_deduct', 2)
                    ->where('add_time', 'between', [$monthBeginDate, $monthendDate])
                    ->limit(0, 3)
                    ->order('add_time asc')
                    ->field('id,add_time')
                    ->select();
            $num2 = count($wenjuan2);
            if ($num2 == 3) {
                Db::name('survey_logs')
                        ->where('id', 'in', [$wenjuan2[0]['id'], $wenjuan2[1]['id'], $wenjuan2[2]['id']])
                        ->update(['is_deduct' => 1]);

                $wenjuan2data['staff_id'] = $staff_id;
                $wenjuan2data['type'] = 2;
                $wenjuan2data['score_type'] = 13;
                $wenjuan2data['score'] = -3;
                $wenjuan2data['remarks'] = '行为不文明，减3分';
                $wenjuan2data['order_id'] = $wenjuan2[2]['id'];
                $wenjuan2data['add_time'] = $wenjuan2[2]['add_time'];
                Db::name('staff_assess_score')->insert($wenjuan2data);
            }

            //【服务分】未佩戴口罩，或卫生脏乱，减4分  #根据问卷调查  累计3次扣分
            $wenjuan3 = Db::name('survey_logs')
                    ->where('staff_id', $staff_id)
                    ->where('type', 14)
                    ->where('yes_no', 0)
                    ->where('is_deduct', 2)
                    ->where('add_time', 'between', [$monthBeginDate, $monthendDate])
                    ->limit(0, 3)
                    ->order('add_time asc')
                    ->field('id,add_time')
                    ->select();
            $num3 = count($wenjuan3);
            if ($num3 == 3) {
                Db::name('survey_logs')
                        ->where('id', 'in', [$wenjuan3[0]['id'], $wenjuan3[1]['id'], $wenjuan3[2]['id']])
                        ->update(['is_deduct' => 1]);

                $wenjuan3data['staff_id'] = $staff_id;
                $wenjuan3data['type'] = 2;
                $wenjuan3data['score_type'] = 14;
                $wenjuan3data['score'] = -4;
                $wenjuan3data['remarks'] = '未佩戴口罩，或卫生脏乱，减4分';
                $wenjuan3data['order_id'] = $wenjuan3[2]['id'];
                $wenjuan3data['add_time'] = $wenjuan3[2]['add_time'];
                Db::name('staff_assess_score')->insert($wenjuan3data);
            }

            //【服务分】服务态度不佳，减5分  #根据问卷调查  累计3次扣分
            $wenjuan4 = Db::name('survey_logs')
                    ->where('staff_id', $staff_id)
                    ->where('type', 15)
                    ->where('yes_no', 0)
                    ->where('is_deduct', 2)
                    ->where('add_time', 'between', [$monthBeginDate, $monthendDate])
                    ->limit(0, 3)
                    ->order('add_time asc')
                    ->field('id,add_time')
                    ->select();
            $num4 = count($wenjuan4);
            if ($num4 == 3) {
                Db::name('survey_logs')
                        ->where('id', 'in', [$wenjuan4[0]['id'], $wenjuan4[1]['id'], $wenjuan4[2]['id']])
                        ->update(['is_deduct' => 1]);

                $wenjuan4data['staff_id'] = $staff_id;
                $wenjuan4data['type'] = 2;
                $wenjuan4data['score_type'] = 15;
                $wenjuan4data['score'] = -5;
                $wenjuan4data['remarks'] = '服务态度不佳，减5分';
                $wenjuan4data['order_id'] = $wenjuan4[2]['id'];
                $wenjuan4data['add_time'] = $wenjuan4[2]['add_time'];
                Db::name('staff_assess_score')->insert($wenjuan4data);
            }
        }
        return Utils::ajaxReturn(0, '成功', null);
    }

    public function aaa() {
        $file = new File();
        $aaa = $file->generateStaffTeamQrcode(1);
        print_r($aaa);
    }

    /*
     * 招募美容师
     * 日期 2021-04-16
     */

    public function addStaffEnlist() {
        $rule = [
            'ctm_id' => 'require',
            'name' => 'require',
            'sex' => 'require',
            'age_limit' => 'require',
            'reason' => 'require',
        ];
        $msg = [
            'ctm_id.require' => '用户id必须',
            'name.require' => '姓名必须',
            'sex.require' => '性别必须',
            'age_limit.require' => '工作年限必须',
            'reason.require' => '加入理由必须',
        ];

        $all = input('param.');

        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();

            return Utils::ajaxReturn(1, $error, null);
        }

        $ctm_id = $all['ctm_id'];
        $name = $all['name'];
        $sex = $all['sex'];
        $age_limit = $all['age_limit'];
        $reason = $all['reason'];
        $note = input('param.note');

        //查询用户有没有提交过
        $row = StaffEnlist::where('ctm_id', $ctm_id)->find();
        if ($row) {
            return Utils::ajaxReturn(60000, '您已经申请过了，请耐心等待', null);
        }

        //写入数据
        $staffCtmResult = StaffEnlist::insert([
                    'ctm_id' => $ctm_id,
                    'name' => $name,
                    'sex' => $sex,
                    'age_limit' => $age_limit,
                    'reason' => $reason,
                    'note' => $note,
                    'add_time' => date('Y-m-d H:i:s'),
        ]);
        if ($staffCtmResult) {
            return Utils::ajaxReturn(0, '添加成功', null);
        }
    }
    
    /*
     * 招募美容师加入理由标签
     * 日期 2021-04-16
     */

    public function staffEnlistLabel() {
        $list = Db::table('sys_dictionary')
                ->where('type','STAFF_ENLIST_LABEL')
                ->where('active',0)
                ->field('id,view')
                ->select();
        return Utils::ajaxReturn(0, '查询成功', $list);
    }

}
